<?php
/**
 * QRcode.php
 * Notes:二维码
 * author: chen
 * DateTime: 2022/5/5 16:45
 * @package Xtsb\Cims\Qrcode
 */

namespace Xtsb\Cims\QRcode;

use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode as QR;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

class QRcode
{
  /**
   * Notes:
   * author: chen
   * DateTime: 2022/5/5 17:36
   * @param string $contentText 二维码内容
   * @param null $filename 二维码文件名称
   * @param null $logo 二维码嵌套logo
   * @param null $label 二维码说明
   * @param false $isSave 是否保存二维码
   * @return array
   * @throws \Exception
   */
  public static function qrcode($contentText = 'https://baidu.com', $filename = null, $logo = null, $label = null, $isSave = false)
  {
    $writer = new PngWriter();
    $qrCode = QR::create($contentText)//跳转的url地址
    ->setEncoding(new Encoding('UTF-8'))
      ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
      ->setSize(300)//大小
      ->setMargin(10)//边距
      ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
      ->setForegroundColor(new Color(0, 0, 0))
      ->setBackgroundColor(new Color(255, 255, 255));

    //嵌套logo
    if (isset($logo) && is_file('.' . $logo)) {
      $logo = Logo::create('.' . $logo)->setResizeToWidth(60)->setResizeToHeight(60);
    }

    //二维码下面的文字
    if (isset($label)) {
      $label = Label::create($label)->setTextColor(new Color(0, 0, 0));
    }

    $result = $writer->write($qrCode, $logo, $label);

    if (!isset($filename)) {
      $qrcodeName = date('YmdHis') . '.png';
    } else {
      $qrcodeName = $filename . '.png';//二维码文件名称
    }

    //    header('Content-Type: '.$result->getMimeType());
    $result->getString();

    if ($isSave) {
      //保存二维码文件
      $result->saveToFile('/qrcode/' . $qrcodeName);

      $res['filepath'] = '/qrcode/' . $qrcodeName;
    } else {
      //下载base64文件流
      $res['file'] = $result->getDataUri();//生成二维码base64字符串
      $res['filename'] = $qrcodeName;
      $res['mime_type'] = 'png';
      //    @unlink('./' . $zipName);//删除临时文件
    }

    return $res;
  }
}
